<?php

namespace catchAdmin\externalGoods\controller;

use catchAdmin\externalGoods\model\Notify as externalNotifyModel;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;
use catchAdmin\product\service\CategoryService;
use catchAdmin\externalGoods\service\GoodsService as externalGoodsService;
use catcher\base\CatchRequest as Request;
use houniao\tools\Params;
use think\Exception;
use think\Request as ThinkRequest;
use catcher\CatchAdmin;
use catcher\CatchAuth;
use catcher\CatchResponse;
use houniao\api\v1\Goods as GoodsApi;

class Notify extends CatchAdmin
{

    protected $app_key = '62ae4e5e226a972c';
    protected $secret='2b7db6bdb6cc689de3cda48a4fe80095';


    public function __construct(externalNotifyModel $externalNotifyModel)
    {
        $this->externalNotifyModel = $externalNotifyModel;
    }

    public function index(CatchAuth $auth, Request $request)
    {
        return CatchResponse::paginate($this->externalNotifyModel->getList());
    }

    public function triggerGoods(CatchAuth $auth, Request $request){
        $type = $request->post('type');
        $goods_spu = $request->post('goods_spu');
        $goods_info = (new externalGoodsModel)
            ->field('supplier_id,goods_name')
            ->where('goods_spu',$goods_spu)->find();

        if(1 !=  $goods_info['supplier_id']){
            return CatchResponse::fail('该商品暂不支持通知');
        }

        $data = [
            'type'=>$type,
            'data'=>[
                'goods_spu'=>$goods_spu,
                'goods_name'=>$goods_info['goods_name'],
                'old_goods_spu'=>'',
            ]
        ];
        $data['sign'] = $this->_getSign($data);

        $request =  $this->_post($data);
        if(1 ==  $request['status']){
            return CatchResponse::success();
        }else{
            return CatchResponse::fail('操作失败'.$request['msg']);
        }
    }

    public function triggerOrder(){

    }

    private function _getSign($data){
        $data['app_key'] = $this->app_key;

        $data =  Params::paraFilter($data);

        //对待签名参数数组排序
        $old = $data;
        $data = Params::argSort($data);

        //生成签名结果
        $makeSign = Params::buildRequestMysign($data,$this->secret);

        return $makeSign;
    }

    private function _post($req_data){
        $client = new \GuzzleHttp\Client([
            'base_uri' => 'http://cross.qekj.net', // 替换为你的 WordPress 站点 URL
            'timeout'  => 20,
            'headers'=>[
                'Connection' => 'close', // 关闭 Keep-Alive
            ]
        ]);

        try {
            $response = $client->post('/callback/houniao', [
                'headers' => [
//                    'X-API-KEY' => $api_key, // 如果你设置了 API 密钥
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ],
                'form_params' => $req_data,
            ]);

            // 解析响应
            $body = $response->getBody();

            //file_put_contents('a.html',$body);

            $data = json_decode($body, true);

            //throw new Exception($body);

            // 处理响应数据
            if (isset($data['code']) && $data['code'] == 200) {
                return ['status' => 1];
            } else {
                return ['status'=>0,'msg'=>'通知失败'];
            }

        } catch (\Exception $e) {// 处理请求异常
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }


}